from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from goods.models import SKU, GoodsCategory, SPU
from meiduo_admin.utils.paginator import PageNum
from meiduo_admin.serializers.skus import SKUSerializer, GoodsCategorySerializer, SPUSpecificationSerializer


"""
{
    "counts": "商品SPU总数量",
    "lists": [
        {
            "id": "商品SKU ID",
            "name": "商品SKU名称",
            "spu": "商品SPU名称",
            "spu_id": "商品SPU ID",
            "caption": "商品副标题",
            "category_id": "三级分类id",
            "category": "三级分类名称",
            "price": "价格",
            "cost_price": "进价",
            "market_price": "市场价格",
            "stock": "库存",
            "sales": "销量",
            "is_launched": "上下架",
            "specs": [
                {
                    "spec_id": "规格id",
                    "option_id": "选项id"
                },
                ...
            ]
        },
        ...
    ],
    "page": "页码",
    "pages": "总页数",
    "pagesize": "页容量"
}
"""


class SKUView(ModelViewSet):
    """
    实现sku信息的增删改查
    """
    permission_classes = (IsAdminUser, )
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer
    pagination_class = PageNum

    def category(self, request):
        """
            获取商品种类
        """
        categories = GoodsCategory.objects.filter(subs__id=None)
        ser = GoodsCategorySerializer(categories, many=True)

        return Response(ser.data)

    def specs(self, request, pk):
        """
            获取商品规格信息
        """
        # 1. 获取当前商品的规格信息
        spu = SPU.objects.get(id=pk)
        specs = spu.specs.all()

        # 2. 通过规格信息获取规格选项，并进行序列化操作
        ser = SPUSpecificationSerializer(specs, many=True)

        # 3. 响应结果
        return Response(ser.data)


